package pers.li.controller.goods;

import pers.li.model.TO.CarTO;
import pers.li.model.VO.CarVO;
import pers.li.service.CarService;
import pers.li.utils.JsonUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;

@WebServlet("/goods/addCart.action")
public class AddCartController extends HttpServlet {
    private final CarService carService = new CarService();

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        BufferedReader br = req.getReader();
        //2.读取数据
        String line = null;
        String body = null;
        while ((line = br.readLine()) != null) {
            body = line;
        }
        CarTO carTO = JsonUtil.parseObject(body, CarTO.class);
        CarVO carVO = carService.getCarVOByTO(carTO);
        HttpSession session = req.getSession();
        List<CarVO> carVOS = new ArrayList<>();
        Object car = session.getAttribute("car");
        if (car != null)
            carVOS = (List<CarVO>) car;
        carVOS.add(carVO);
        session.setAttribute("car", carVOS);
        session.setAttribute("carJson",JsonUtil.toJsonString(carVOS));
        Map<String, Object> res = new HashMap<>();
        resp.setContentType("application/json;charset=utf-8");
        PrintWriter writer = resp.getWriter();
        res.put("success", true);
        res.put("cartnum", carVOS.size());
        writer.print(JsonUtil.toJsonString(res));
        writer.flush();
        writer.close();
    }

}
